<?php

namespace app\api\controller\applets;

use app\api\model\Car;
use app\api\model\CarCate;
use app\api\model\Label;
use app\api\model\Merchant;
use app\api\model\MerchantCar;
use app\common\controller\Api;
use fast\Random;
use think\App;
use think\Db;
use think\db\Query;
use think\facade\Validate;
use think\facade\Config;
use think\Request;

/**
 * 首页接口.
 */
class Index extends Api
{
    protected $noNeedLogin = ['config','indexUp','carCate','carList','merchantCarList'];
    protected $noNeedRight = '*';

    protected $model;
    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        parent::__construct(App::getInstance());
        $this->model = new \app\api\model\User();
    }


    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 公共参数.
     */
    public function config()
    {
        $config = \app\api\model\Config::config();
        //取消类别
        $cancel_type = \app\api\model\Order::fetchCancelType();
        $config['cancel_type'] = $cancel_type;
        $data = ['status' => 1, 'message' => '操作成功', 'result' => $config];
        $this->getReturnData($data);
    }

    /**
     * 首页轮播时间.
     */
    public function indexUp()
    {
        $requestData = $this->request->post();
        //轮播图
        $banner_list = \app\api\model\Config::configFind(['name' => 'sys_banner']);
        $banner_list = explode(',', $banner_list);
        $week_list = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        //默认时间
        $start_time = [
            'day' => date('n月j日', strtotime('+1 day')),
            'time' => '10:00',
            'week' => $week_list[date('w', strtotime('+1 day'))],
            'start_stamp' => strtotime(date('Y-m-d', strtotime('+1 day')).' 10:00'),
            'year_day' => date('Y-n-j', strtotime('+1 day'))
        ];
        $end_time = [
            'day' => date('n月j日', strtotime('+3 day')),
            'time' => '10:00',
            'week' => $week_list[date('w', strtotime('+3 day'))],
            'end_stamp' => strtotime(date('Y-m-d', strtotime('+3 day')).' 10:00'),
            'year_day' => date('Y-n-j', strtotime('+3 day'))
        ];
        //新手指导
        $guide_notice = \app\api\model\Config::where('name', 'guide_notice')->value('value');
        $data  = [
            'banner_list' => $banner_list,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'days' => 2,
            'guide_notice' => $guide_notice
        ];
        $requestData = ['status' => 1, 'message' => '操作成功', 'result' => $data];
        $this->getReturnData($requestData);
    }


    /**
     * 车辆品牌和配置.
     */
    public function carCate(){
        $requestData = $this->request->post();
        $merchant_id = $requestData['merchant_id']??0;
        $brand_where = ['type' => 1];
        if($merchant_id){
            $car_id_list = MerchantCar::where([['merchant_id', '=', $merchant_id], ['status', '=',  1], ['is_delete', '=', 1], ['examine_status', '=', 2]])->column('car_id');
            $brand_id_list = Car::where(['id' => $car_id_list])->column('brand_id');
            $brand_where = ['type' => 1, 'id' => $brand_id_list];
        }
        $brand_list = CarCate::getList($brand_where, 'id,cate_name', 'sort desc');
        $configure_list = CarCate::getList(['type' => 2], 'id,cate_name', 'sort desc');
        $list = [
            'brand_list' => $brand_list,
            'configure_list' => $configure_list,
        ];
        $requestData = ['status' => 1, 'message' => '操作成功', 'result' => $list];
        $this->getReturnData($requestData);
    }

    /**
     * 车辆列表.
     */
    public function carList()
    {
        $requestData = $this->request->post();
        $city = $requestData['city']??'';
        if(!$city){
            $requestData = ['status' => 0, 'message' => '请选择城市', 'result' => ''];
            $this->getReturnData($requestData);
        }
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $brand_id = $requestData['brand_id']??0;
        $model_id = $requestData['model_id']??0;
        $price = $requestData['price']??'';
        $service = $requestData['service']??'';
        $is_hot = $requestData['is_hot']??0;
        $where = [['status', '=',  1], ['is_delete', '=', 1], ['is_hot', '=', 2]];
        if($brand_id){
            $where[] = ['brand_id', '=', $brand_id];
        }
        if($model_id){
            $where[] = ['model_id', '=', $model_id];
        }
        $merchant_where = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 2]];
        $like_where = "";
        if($service) {
            $service = explode(',', $service);
            foreach ($service as $ss) {
                $like_where .= "`service` like '%$ss%' or";
            }
            $like_where = rtrim($like_where, ' or');
        }
        if(in_array($city, ['北京市', '天津市', '重庆市', '上海市'])){
            $merchant_where[] = ['province|city', '=', $city];
            $merchant_id_list = Merchant::where($merchant_where)->where($like_where)->column('id');
        }else{
            $merchant_where[] = ['city', 'like', '%'.$city.'%'];
            $merchant_id_list = Merchant::where($merchant_where)->where($like_where)->column('id');
        }
        $merchant_car_where = ['is_delete' => 1, 'status' => 1, 'examine_status' => 2, 'car_status' => 1, 'merchant_id' => $merchant_id_list];
        $builder = Car::field('id,car_name,car_image,car_site,car_gate,car_gear,drive,displacement,sort,createtime')->with(['merchantCar' => function (Query $query) use ($merchant_car_where) {
            $query->field('car_id,car_label,car_price')->where($merchant_car_where)->order('car_price', 'asc');
        }])
            ->where($where);
        if($is_hot > 0){
            $builder->where('is_hot', 2);
        }
//        $list = $builder->order('createtime desc')->fetchSql()->select();
        $list = $builder->order('sort desc')->select()->toArray();
        $car_label_list = Label::where(['is_delete' => 1])->column('name', 'id');
        if($list){
            foreach ($list as $key=>$value){
                $car_gear = MerchantCar::fetchCarGear($value['car_gear']);
                $list[$key]['car_label'] = $value['car_site'].'座|'.$value['car_gate'].'门|'.$car_gear.'|'.$value['displacement'];
                $list[$key]['drive'] = $value['drive'] . 'L';
                $list[$key]['merchant_car_count'] = count($value['merchantCar']);
                if(!$value['merchantCar']){
                    unset($list[$key]);
                }else{
                    $list[$key]['car_price'] = floatval($value['merchantCar'][0]['car_price']);
                    $car_label = array_unique(explode(',', implode(',', array_column($value['merchantCar'], 'car_label'))));
                    $car_labels = '';
                    foreach ($car_label as $kk=>$vv){
                        if(isset($car_label_list[$vv])){
                            $car_labels .= $car_label_list[$vv] . ',';
                        }
                    }
                    $list[$key]['car_labels'] = rtrim($car_labels, ',');
                    unset($list[$key]['merchantCar']);
                }

            }
        }
        if($price && $list){
            $sort_column = array_column($list, 'car_price');
            $sort_name = array_column($list, 'createtime');
            if($price == 'asc'){
                array_multisort($sort_column, SORT_ASC, $sort_name, SORT_DESC, $list);
            }else{
                array_multisort($sort_column, SORT_DESC, $sort_name, SORT_DESC, $list);
            }

        }

        $offset = ($page - 1) * $limit;
        $list = array_slice($list, $offset, $limit);
        $requestData = ['status' => 1, 'message' => '操作成功', 'result' => $list];
        $this->getReturnData($requestData);
    }

    /**
     * 商家车辆列表.
     */
    public function merchantCarList()
    {
        $requestData = $this->request->post();
        $car_id = $requestData['car_id']??0;
        if(!$car_id){
            $requestData = ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        $city = $requestData['city']??'';
        if(!$city){
            $requestData = ['status' => 0, 'message' => '请选择城市', 'result' => ''];
            $this->getReturnData($requestData);
        }
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??6;
        $latitude = $requestData['latitude']??0;
        $longitude = $requestData['longitude']??0;
        if(!$longitude || !$latitude){
            return ['status' => 0, 'message' => '用户定位为空', 'result' => ''];
        }
        $distance = $requestData['distance']??0;
        $price = $requestData['price']??'';
        $service = $requestData['service']??'';
        $where = [['status', '=',  1], ['is_delete', '=', 1], ['examine_status', '=', 2], ['car_status', '=', 1], ['car_id', '=', $car_id]];
        $merchant_where = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 2]];
        $like_where = "";
        if($service) {
            $service = explode(',', $service);
            foreach ($service as $ss) {
                $like_where .= "`service` like '%$ss%' or";
            }
            $like_where = rtrim($like_where, ' or');
        }
        if(in_array($city, ['北京市', '天津市', '重庆市', '上海市'])){
            $merchant_where[] = ['province|city', '=', $city];
            $merchant_id_list = Merchant::where($merchant_where)->where($like_where)->column('id');
        }else{
            $merchant_where[] = ['city', 'like', '%'.$city.'%'];
            $merchant_id_list = Merchant::where($merchant_where)->where($like_where)->column('id');
        }
        $where[] = ['merchant_id', 'in', $merchant_id_list];
        $builder = MerchantCar::with(['carss', 'merchants'])
            ->field("id,car_id,merchant_id,merchant_car_name,car_label,car_price,drive,displacement,merchant_longitude,merchant_latitude,(6378.138 * 2 * asin(sqrt(pow(sin((merchant_latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(merchant_latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((merchant_longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->where($where);
        if($price){
            $builder->order('car_price '. $price . ',distance asc,merchant_id asc');
        }else{
            $builder->order('distance asc,merchant_id asc');
        }
        if($distance){
            $builder->having('distance<='.$distance);
        }
        $list = $builder
            ->page($page, $limit)
            ->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $car_gear = MerchantCar::fetchCarGear($value['car_gear']);
                $value['car_sign'] = $value['car_site'].'座|'.$value['car_gate'].'门|'.$car_gear. '|'. $value['displacement'];
                $value['drive'] = $value['drive'] . 'L';
                $value['address'] = $value['province'] . $value['city'] . $value['area'] . $value['street'];
                $labels = '';
                if($value['car_label']){
                    $labels = Label::where('id', 'in', $value['car_label'])->column('name');
                    $labels = implode(',', $labels);
                }
                $value['car_label'] = $labels;
                $service_list = explode(',', $value['service']);
                foreach ($service_list as $k => $v){
                    $service_list[$k] = Merchant::serviceList($v);
                }
                $service_data = implode(',', $service_list);
                $value['service'] = $service_data;
                $value['car_price'] = floatval($value['car_price']);
                unset($value['merchant_car']);
                $list[$key] = $value;
            }
        }
        $requestData = ['status' => 1, 'message' => '操作成功', 'result' => $list];
        $this->getReturnData($requestData);
    }
}
